﻿using System.Xml.Linq;

namespace TKT.Lifter.CIM.Lifter.TibcoMsg
{
    public class MessageHeader
    {
        public string MessageName { get; set; }

        public string MachineName { get; set; }

        public string TransactionId { get; set; }

        public string OriginalSourceSubjectName { get; set; }

        public string EventUser { get; set; }

        public string EventComment { get; set; }

        public XElement toXElement()
        {
            XElement header = new XElement("Header");

            header.Add(new XElement("MESSAGENAME", this.MessageName));
            header.Add(new XElement("MACHINENAME", this.MachineName));
            header.Add(new XElement("TRANSACTIONID", this.TransactionId));
            header.Add(new XElement("ORIGINALSOURCESUBJECTNAME", this.OriginalSourceSubjectName));
            header.Add(new XElement("EVENTUSER", this.EventUser));
            header.Add(new XElement("EVENTCOMMENT", this.EventComment));

            return header;
        }

        public void Parse(XElement header)
        {
            this.MessageName = header.Element("MESSAGENAME").Value;
            this.MachineName = header.Element("MACHINENAME").Value;
            this.TransactionId = header.Element("TRANSACTIONID").Value;
            this.OriginalSourceSubjectName = header.Element("ORIGINALSOURCESUBJECTNAME").Value;
            this.EventUser = header.Element("EVENTUSER").Value;
            this.EventComment = header.Element("EVENTCOMMENT").Value;
        }

        public void Parse(TIBCO.Rendezvous.Message message)
        {
            TIBCO.Rendezvous.MessageField field = message.GetField("Message");
            if (field == null)
            {
                field = message.GetField("xmlData");
            }
            string strXML = field.Value as string;
            XElement root = XElement.Parse(strXML);
            XElement header = root.Element("Header");
            this.Parse(header);
        }
    }
}
